import { DataSet } from 'choerodon-ui/pro';
import { CONSTANTS } from '@choerodon/master';
import JSONbig from 'json-bigint';
import { hostApi, hostApiConfig } from '@/api';
import {
  productTypeData,
  deployWayData,
  preCommandDefault,
  runCommandDefault,
  postCommandDefault,
  dockerCommandDefault,
  killCommandDefault,
  healthProbDefault,
  valueDefault,
  dockerComposeRunCommandDefault,
} from './constants';

const {
  LCLETTER_NUMREGEX,
} = CONSTANTS;

const Index: any = ({
  HotJarOptionsDataSet,
  hostGroupDeploy,
  deployPayloadTypeName,
  projectId,
  useStore,
  level,
}: any) => ({
  autoCreate: true,
  fields: [{
    defaultValue: productTypeData[0].value,
    textField: 'name',
    valueField: 'value',
    name: 'hostDeployType',
    type: 'string',
    label: '应用类型',
    disabled: level !== 'project' || window.location.href.includes('project-pipeline-template'),
    options: new DataSet({
      data: [
        ...productTypeData.slice(0, 2),
        productTypeData[3],
        productTypeData[2],
      ],
    }),
  }, {
    textField: 'name',
    valueField: 'value',
    defaultValue: deployWayData[0].value,
    name: 'deployType',
    type: 'string',
    label: '部署方式',
    disabled: level !== 'project' || window.location.href.includes('project-pipeline-template'),
    options: new DataSet({
      data: deployWayData,
    }),
  }, {
    name: 'appName',
    type: 'string',
    label: '应用名称',
    required: level === 'project' && !window.location.href.includes('project-pipeline-template'),
    textField: 'name',
    valueField: 'id',
    disabled: level !== 'project' || window.location.href.includes('project-pipeline-template'),
    options: HotJarOptionsDataSet,
    validator: async (value: string, type: string, record: any) => {
      if (value) {
        // 部署载体为主机组名称不需要校验
      // 这一块是inject 有问题找jieming
        if (hostGroupDeploy && record?.get(deployPayloadTypeName) === 'group') {
          return true;
        }
        const isCreate = record?.get('deployType') === deployWayData[0].value;
        if (isCreate) {
          const flag = await hostApi.checkAppName(value);
          if (flag) {
            return true;
          }
          return '应用名称已重复';
        }
        return true;
      }
      return true;
    },
  }, {
    name: 'appCode',
    type: 'string',
    label: '应用编码',
    required: level === 'project' && !window.location.href.includes('project-pipeline-template'),
    validator: (value:string) => {
      let flag: any = true;
      if (!LCLETTER_NUMREGEX.regex.test(value)) {
        flag = LCLETTER_NUMREGEX.text;
      }
      return flag;
    },
    dynamicProps: {
      disabled: ({ record }:any) => (record?.get('deployType') === deployWayData[1].value)
      || level !== 'project' || window.location.href.includes('project-pipeline-template'),
    },
  }, !hostGroupDeploy ? {
    name: 'hostId',
    type: 'object',
    label: '主机',
    textField: 'name',
    valueField: 'id',
    required: level === 'project' && !window.location.href.includes('project-pipeline-template'),
    dynamicProps: {
      disabled: ({ record }: any) => record?.get('deployType') === deployWayData[1].value
      || level !== 'project' || window.location.href.includes('project-pipeline-template'),
    },
    lookupAxiosConfig: ({ params }: any) => {
      const data = params?.search_param;
      return projectId ? ({
        method: 'post',
        // 这里取消了random
        url: `/devops/v1/projects/${projectId}/hosts/page_by_options`,
        data: {
          searchParam: {
            type: 'deploy',
          },
          params: [data],
        },
        transformResponse: (res: any) => {
          let newRes = res;
          try {
            newRes = JSONbig.parse(newRes);
            newRes.content = newRes.content.map((i: any) => ({
              ...i,
              connect: i.hostStatus === 'connected',
            }));
            useStore.setHostList(newRes.content);
            return newRes;
          } catch (e) {
            return newRes;
          }
        },
      }) : undefined;
    },
  } : {}, {
    name: 'deploySource',
    type: 'string',
    disabled: true,
    label: '部署来源',
    defaultValue: 'pipelineDeploy',
    textField: 'text',
    valueField: 'value',
    dynamicProps: {
      required: ({ record }: any) => (record?.get('hostDeployType') === 'image'
            || ['jar', 'docker'].includes(record?.get('hostDeployType'))),
    },
    options: new DataSet({
      data: [{
        value: 'matchDeploy',
        text: '匹配制品部署',
      }, {
        value: 'pipelineDeploy',
        text: '流水线制品部署',
      }],
    }),
  }, {
    name: 'pipelineTask',
    type: 'string',
    label: '关联构建任务',
    textField: 'pipelineTask',
    valueField: 'pipelineTask',
    disabled: level !== 'project' || window.location.href.includes('project-pipeline-template'),
    dynamicProps: {
      required: ({ record }: any) => level === 'project' && !window.location.href.includes('project-pipeline-template')
      && ((((record?.get('hostDeployType') === 'image'
            && record?.get('deploySource') === 'pipelineDeploy')
            || ['jar', 'docker'].includes(record?.get('hostDeployType'))
              && record?.get('deploySource') === 'pipelineDeploy')) || (
        (record?.get('hostDeployType') === 'docker_compose')
      )),
    },
  }, {
    name: 'preCommand',
    type: 'string',
    defaultValue: preCommandDefault,
  }, {
    name: 'runCommand',
    type: 'string',
    defaultValue: runCommandDefault,
  }, {
    name: 'postCommand',
    type: 'string',
    defaultValue: postCommandDefault,
  }, {
    name: 'dockerCommand',
    type: 'string',
    defaultValue: dockerCommandDefault,
  }, {
    name: 'killCommand',
    type: 'string',
    defaultValue: killCommandDefault,
  }, {
    name: 'healthProb',
    type: 'string',
    defaultValue: healthProbDefault,
  }, {
    name: 'containerName',
    type: 'string',
    label: '容器名称',
    required: true,
    disabled: level !== 'project' || window.location.href.includes('project-pipeline-template'),
    dynamicProps: {
      required: ({ record }: any) => (
        record?.get('type') === 'cdHost'
            && ['docker', 'image'].includes(record?.get('hostDeployType'))
            && ((record?.get('deploySource') === 'matchDeploy'
              || record?.get('deploySource') === 'pipelineDeploy')
            || (record?.get('deploySource') === 'pipelineDeploy'
              || record?.get('hostDeployType') === 'docker'))
      ),
    },
  }, {
    name: 'value',
    type: 'string',
    defaultValue: valueDefault,
  }, {
    name: 'dockerComposeRunCommand',
    type: 'string',
    defaultValue: dockerComposeRunCommandDefault,
  }],
  events: {
    update: ({ name, value, record }: any) => {
      switch (name) {
        case 'appName': {
          if (record?.get('deployType') === deployWayData[1].value) {
            const data = record?.getField('appName')?.options?.toData();
            const item = data.find((i: any) => i.id === value);
            record.set('appCode', item?.code);
            record.set('hostId', item?.hostId);
          }
          break;
        }
        case 'hostDeployType': {
          HotJarOptionsDataSet.setQueryParameter('type', value);
          HotJarOptionsDataSet.query();
          record.set('appName', undefined);
          record.set('appCode', undefined);
          record.set('hostId', undefined);
          break;
        }
        default: {
          break;
        }
      }
    },
    load: ({ dataSet }: any) => {
      const hostDeployType = dataSet?.current?.get('hostDeployType');
      HotJarOptionsDataSet.setQueryParameter('type', hostDeployType);
      HotJarOptionsDataSet.query();
    },
  },
});

export default Index;
